package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Vector;

import entidades.Tema;

public class TemasDAO {

	public static void cargarTemas(Vector<Tema> listaTemas) throws SQLException {
		if (listaTemas.size() != 0) {

			Connection conexion = PrincipalDAO.connect();
		
			String sql ="INSERT INTO `temas` ( " +
						"	`id`, `idDisco`, `idGrupo`, `nombreTema` , `url` " +
						" ) " +
						" VALUES ( ?, ?, ?, ?, ? )";
			
			PreparedStatement prep = conexion.prepareStatement(sql);

			for (int i=0; i < listaTemas.size(); i++) {
				prep.setInt(1, listaTemas.elementAt(i).getIdTema());
				prep.setInt(2, listaTemas.elementAt(i).getIdDisco());
				prep.setInt(3, listaTemas.elementAt(i).getIdGrupo());
				prep.setString(4, listaTemas.elementAt(i).getTitle());
				prep.setString(5, listaTemas.elementAt(i).getUrl());
				prep.addBatch();
			}
	
			conexion.setAutoCommit(false);
			prep.executeBatch();
			conexion.setAutoCommit(true);
			conexion.close();
		}	
	}
	
	public static void crearTablaTemas() throws SQLException {
		
		Connection conexion = PrincipalDAO.connect();
		Statement statement = conexion.createStatement();
		
		statement.execute("DROP TABLE  IF EXISTS `temas`");
		String sql =" CREATE TABLE temas ( " +
					" `id` INT NOT NULL , " +
					" `idDisco` INT NOT NULL , " +
					" `idGrupo` INT NOT NULL , " +
					" `nombreTema` VARCHAR( 150 ) NOT NULL , " +
					" `url` VARCHAR( 200 ) NOT NULL ,PRIMARY KEY ( `id` ) ,UNIQUE (`url`) " +
					" ); ";
		
		//System.out.println(sql);
		statement.executeUpdate(sql);
		conexion.close();
	
	}

	public static int getIdUltimoTema() throws SQLException {
		Connection conexion = PrincipalDAO.connect();
		Statement statement = conexion.createStatement();
		
		String sql =" SELECT MAX(`id`) AS idFinal " +
					" FROM temas ";
		
		//System.out.println(sql);
		ResultSet rs = statement.executeQuery(sql);
		Integer maxId;
		
		if (rs.next()) {
			maxId = rs.getInt("idFinal");
			System.out.println("Maximo id tema : " + maxId);
		}
		else 
			maxId = 0;			
		
		conexion.close();
		rs.close();
		return maxId;
	}

	public static Hashtable<String, Integer> temasYaCargados() throws SQLException {
		Hashtable<String, Integer> idTema = new Hashtable<String, Integer>();

		Connection conexion = PrincipalDAO.connect();
		Statement statement = conexion.createStatement();
		
		String sql =" SELECT * " +
					" FROM temas ";
		
		//System.out.println(sql);
		ResultSet rs = statement.executeQuery(sql);
		Integer id;
		String url;
		
		while (rs.next()) {
			id = rs.getInt("id");
			url = rs.getString("url");
			//System.out.println(url);
			idTema.put(url, id);
		}
		
		conexion.close();
		rs.close();
		
		return idTema;
	}

}
